package com.wanmait.recruit.filter;

import com.wanmait.recruit.pojo.CompanyAdmin;
import com.wanmait.recruit.pojo.CompanyHr;
import com.wanmait.recruit.pojo.Person;
import com.wanmait.recruit.service.CompanyAdminService;
import com.wanmait.recruit.service.CompanyHrService;
import com.wanmait.recruit.service.CompanyAdminService;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/web/company/manage/*")
public class CompanyManageFilter implements Filter {

    private CompanyAdminService companyAdminService;
    private CompanyHrService companyHrService;

    @Override//注入service
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();
        WebApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        if(cxt != null && cxt.getBean(CompanyAdminService.class) != null && companyAdminService == null){
            companyAdminService =cxt.getBean(CompanyAdminService.class);
        }
        if(cxt != null && cxt.getBean(CompanyHrService.class) != null && companyHrService == null){
            companyHrService =cxt.getBean(CompanyHrService.class);
        }
    }


    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse)resp;
        HttpSession session = request.getSession();
        Person person = (Person)session.getAttribute("person");
        if(person==null){
            String path = request.getContextPath();
            response.sendRedirect(path+"/web/index");
            return;
        }
        CompanyHr companyHr = companyHrService.findByPerson(person);
        CompanyAdmin companyAdmin = companyAdminService.findByPerson(person);
        if(companyAdmin==null&&companyHr==null){
            String path = request.getContextPath();
            response.sendRedirect(path+"/web/index?msg=ntExist");
            return;
        }
        chain.doFilter(req,resp);

    }
}
